log = function(msg) {
  if (typeof console == 'object' && console.log) {
    console.log(msg);
  }
}

warn = function(msg) {
  if (typeof console == 'object' && console.warn) {
    console.warn(msg);
  }
}

var appData = null;
var ajaxOptions = null;

var ajax = function(options) {
  options = options || {};
  for(var i in ajaxOptions) {
    options[i] = ajaxOptions[i];
  }

  $.ajax(options);
}

var setHangoutName = function(name, first) {
  $('#txt').css({display: 'block'});
  $('#error').html('');

  if (first) {
    $('#n-ccm nobr').html(name).attr('title', name);
  }

  $('#n-hg span').html(name);
}

var displayError = function(msg) {
  $('#txt').hide();
  $('#error').html(msg);
}

var currentParticipants = [];

var connectToEtrotter = function() {
  var url = gapi.hangout.getHangoutUrl();
  var identity = gapi.hangout.getHangoutId();
  ajax({
    data: {action:'init', url: url, identity: identity},
    success: function() {
      log("Connnect to etrotter successfully. Start to synchronize.");

      $('#n-hg').css({
        cursor:'pointer'
      });

      $('#n-hg').click(function() {
        $('#n-hg').css({
          display:'none'
        });

        $('#name').val($('#n-hg span').html());
        $('#form').css({
          display:'block'
        });

      });

      $('#submit').click(function() {
        var name = $('#name').val();
        if(name) {
          rename(name);
        } else {
          alert('Name should not be null.');
        }
      });

      setHangoutName(appData.name, true);
      gapi.hangout.data.setValue('hangoutName', appData.name);

      var participants = gapi.hangout.getParticipants();
      currentParticipants = participants;

      for(var i in participants) {
        addParticipant(participants[i]);
      }

      gapi.hangout.onParticipantsAdded.add(function(eventObj) {
        var added = eventObj.addedParticipants;

        for(var i in added) {
          addParticipant(added[i]);
        }
      });

      gapi.hangout.onParticipantsRemoved.add(function(eventObj) {
        var removed = eventObj.removedParticipants;

        for(var i in removed) {
          delParticipant(removed[i]);
        }
      });

      var interval = setInterval(function(){
        keepAlive();
      }, 1000 * 30); // keep alive every 30s

    },
    error: function() {
      displayError("Failed to connect to etrotter. Please make sure you login etrotter.");
    }
  });
}

var rename = function(name) {
  ajax({
    data: {action: 'rename', name:name},
  success: function() {
    log("rename successfully.");

    setHangoutName(name);
    $('#form').css({
      display:'none'
    });
    $('#n-hg').css({
      display:'block'
    });

    gapi.hangout.data.setValue('hangoutName', name);
  },
  error: function() {alert("Failed to rename.")}
  });
}

var addUser = function(id_googuser, name, pic, info) {
  ajax({
    data: {action: 'addUser', id_googuser: id_googuser, name: name, pic: pic, info: info},
  success: function() {log('Add user ' + id_googuser + ' ' + name + ' successfully.')},
  error: function() {warn('Failed to add user.')}
  });
}

var delUser = function(id_googuser) {
  ajax({
    data: {action: 'delUser', id_googuser: id_googuser},
  success: function() {log("Delete user " + id_googuser + ' successfully.')},
  error: function() {warn("Failed to delete user.")}
  });
}

var keepAlive = function() {
  ajax({
    data: {action: 'keepAlive'},
  dataType: 'json',
  success: function(data) {
    //$('#n-ccm').val(data.name);
    //$('#n-hg span').html(data.name);
    setHangoutName(data.name);
    gapi.hangout.data.setValue('hangoutName', data.name);
    log("Keep alive successfully.");
  },
  error: function() {warn("Failed to keep alive.")}
  });
}

var addParticipant = function(participant) {
  if(!participant.person) {
    return;
  }

  var person = participant.person;
  var pic = person.image && person.image.url || '';
  var name = person.displayName || 'unknown';
  var id_googuser = person.id;

  if(id_googuser) {
    addUser(id_googuser, name, pic, JSON.stringify(participant));
  }
}

var delParticipant = function(participant) {
  if(!participant.person) {
    return;
  }

  var person = participant.person;
  var id_googuser = person.id;

  if (id_googuser) {
    delUser(id_googuser);
  }
}

onLoad = function() {
  // A function to be run at app initialization time which registers our callbacks
  log('Init app.');

  (function(){
    var retries = 0;
    var interval = setInterval(function(){
      if (!gapi.hangout) {
        displayError('You are not the organizor, Please close this app.');
        clearInterval(interval);
      }

      if (gapi.hangout.isApiReady()) {
        clearInterval(interval);

        try {
          appData = JSON.parse(gadgets.views.getParams()['appData']);
        } catch(e) {
          // Not the organizor show title
          setHangoutName(gapi.hangout.data.getValue('hangoutName'), true);
          $('#n-hg img').hide();
          gapi.hangout.data.onStateChanged.add(function() {
            setHangoutName(gapi.hangout.data.getValue('hangoutName'));
          });
          return;
        }

        ajaxOptions = {
          url: appData.callback,
          type: 'POST',
          xhrFields: {
            withCredentials: true
          }
        };


        connectToEtrotter();

      } else {
        console.log("Hangout api is not ready.");
        if (retries > 100) clearInterval(interval);
        retries++;
      }
    }, 500)}
  )();
}

google.setOnLoadCallback(onLoad);

